from bson import ObjectId

from ioservice.activity import aggregate_activities_raw
from ioservice.activity_institution import delete_activity_institution_by_query
from ioservice.activity_register import delete_activity_registers_by_query
from ioservice.institution import update_institution_served_people_num
from tasks.computing import alumni as alumni_computing
from utils.iterutil import generate_batch
from loguru import logger


async def clear_activity_references(activity_ids):
    """
    删除活动时清理引用关系的操作，需求请看：
    - https://fs1f1atlth.feishu.cn/docs/doccnMYmyK4MLKb5uUYKWBLZsAh#i1i4Ga
    """
    for i, activity_batch in enumerate(generate_batch(activity_ids)):
        oids = [ObjectId(aid) for aid in activity_batch]

        agg_pip = [
            {"$match": {"_id": {"$in": oids}}}, {"$project": {"institution_id": 1}},
            {
                "$lookup": {
                    "from": "activity_register",
                    "let": {"activity_id_var": "$_id"},
                    "pipeline": [
                        {"$match":
                             {"$expr":
                                  {"$eq": ["$$activity_id_var", "$activity_id"]}
                              }
                         },
                        {"$match": {"is_attended": True}}
                    ],
                    "as": "register_record"
                }},
            {"$facet": {
                "person_group": [{"$unwind": "$register_record"}, {"$group": {"_id": "$register_record.person_id"}}],
                "institution_group": [{"$group": {"_id": "$institution_id"}}]
            }}
        ]
        agg_result = await aggregate_activities_raw(agg_pip)
        person_ids = [str(r['_id']) for r in agg_result[0].get("person_group")]
        result = await delete_activity_registers_by_query({"activity_id": {"$in": oids}})
        logger.info(f"TASK INFO::clear_activity_references::activity_id batch {i}::delete_activity_registers {result}")
        if person_ids:
            await alumni_computing.batch_update_computing_fields(person_ids, caller=f"after_delete_activity::activity_id batch {i}")

        result = await delete_activity_institution_by_query({"activity_id": {"$in": oids}})

        logger.info(f"TASK INFO::clear_activity_references::activity_id batch {i}::delete_activity_institution {result}")

        # institution_ids = [str(r['_id']) for r in agg_result[0].get("institution_group")]
        institution_ids = [str(r['_id']) for r in agg_result[0].get("institution_group") if r['_id'] is not None]

        await update_institution_served_people_num(institution_ids)
